﻿using System;
using System.Linq;
using Shell.PocoDot;

namespace Shell.DomainDot
{
    public class WithAll<TDomainDot, TMainPocoDot> : IDisposable
        where TMainPocoDot : PocoDotBase
        where TDomainDot : DomainDotBase<TMainPocoDot>
    {
        private bool disposed;

        public WithAll(IDataContext<TMainPocoDot> repository)
        {
            this.Repository = repository;
        }

        protected IDataContext<TMainPocoDot> Repository { get; private set; }

        public IQueryable<TDomainDot> Instances
        {
            get
            {
                return this.Repository.Read().Select(dot => DomainDotFactory.Factory.Create<TDomainDot, TMainPocoDot>(dot.Id));
            }
        }

        public TDomainDot Create(TMainPocoDot pocoDot)
        {
            pocoDot.Id = Guid.NewGuid();
            var dot = this.Repository.Add(pocoDot);
            this.Submit();
            return DomainDotFactory.Factory.Create<TDomainDot, TMainPocoDot>(dot.Id);
        }

        public void Delete(Guid key)
        {
            this.Repository.Delete(key);
        }

        public int Submit()
        {
            return this.Repository.Submit();
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this.disposed)
                {
                    this.Repository = null;
                }
                this.disposed = true;
            }
        }
    }
}
